<template>
  <div class="all">
    <div class="title">
      <div style="display: flex">
        <div>{{ title }}</div>
        <el-popover
          placement="top-start"
          title="标题"
          width="350"
          trigger="hover"
          content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"
        >
          <svg slot="reference" class="icon" aria-hidden="true">
            <use xlink:href="#icon-wenhao1" />
          </svg>
        </el-popover>
      </div>
      <div style="display: flex">
        <div v-if="canConfirm && editId" class="buttonBox">
          <el-upload v-if="roles.includes('StockEnterUpdate')" :show-file-list="false" action="" :before-upload="file => workbook(file)">
            <el-button type="primary" icon="el-icon-edit" size="mini">{{ $t('button.import') }}</el-button>
          </el-upload>
        </div>
        <el-button v-if="canConfirm && data.parts_list.length > 0 && roles.includes('StockEnterReview')" type="success" icon="el-icon-circle-check" @click="examine">{{ $t('button.verify') }}</el-button>
        <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
        <el-button v-if="roles.includes('StockEnterDelete')" type="danger" icon="el-icon-delete" @click="delBtn">{{ $t('button.delete') }}</el-button>
        <el-button v-if="roles.includes('StockEnterUpdate')" type="primary" icon="el-icon-document-checked" @click="submitForm('form')">保存</el-button>
      </div>
    </div>
    <div class="detail-mid">
      <el-form ref="form" v-loading="loading" :model="data" inline :rules="rules">
        <el-row>
          <el-col :span="4">
            <el-form-item :label="$t('app.stock.enter.coding')" prop="coding">
              <el-input v-model="data.coding" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('app.stock.enter.name')" prop="name">
              <el-input v-model="data.name" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('app.status')" prop="status">
              <SelfSelect v-model="data.status" :clearable="false" disabled :show-list="enterOption" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('app.stock.enter.store')" prop="store_id">
              <Selects v-model="data.store_id" action="storeList" :query="{ kind: 1 }" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('app.stock.enter.source')" prop="type">
              <SelfSelect v-model="data.type" :clearable="false" :show-list="enterType" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('app.sort')" prop="sort">
              <el-input v-model="data.sort" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div v-if="!editId" class="detail-bottom">
      <el-tabs>
        <el-tab-pane :label="$t('app.description')">
          <div style="width: 100%;padding: 2px">
            <TinyMce id="edit" v-model="data.content" :height="250" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div v-if="editId" class="detail-bottom">
      <el-tabs>
        <el-tab-pane label="详细">
          <div class="detail-table">
            <el-table ref="multipleTable" tooltip-effect="dark" width="100%" :data="data.parts_list">
              <el-table-column prop="parts.name" label="备件--编号" align="left" width="200">
                <template scope="scope">
                  <Selects v-show="scope.$index === cellIndex" v-model="editPartsId" action="partsList" :query="{ add_field: 'coding' }" @change="partsChange(editPartsId)" />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.parts_name }}--{{ scope.row.parts_coding }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="number" label="入库数量" align="left" width="80">
                <template slot-scope="scope">
                  <el-input v-show="scope.$index === cellIndex" v-model="editNumber" />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.number }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格" align="left">
                <template slot-scope="scope">
                  <el-input v-show="scope.$index === cellIndex" v-model="editPrice" />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.price }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="apply_date" label="提报日期" align="left" width="180">
                <template slot-scope="scope">
                  <el-date-picker
                    v-show="scope.$index === cellIndex"
                    v-model="editApplyDate"
                    type="date"
                    style="width: 80%"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期时间"
                  />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.apply_date }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="parts_department" label="部门" align="left" width="120">
                <template slot-scope="scope">
                  <el-input v-show="scope.$index === cellIndex" v-model="editDepartment" readonly />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.parts_department }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="parts_category" label="备件类别" align="left" width="150">
                <template slot-scope="scope">
                  <el-input v-show="scope.$index === cellIndex" v-model="editCategory" readonly />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.parts_category }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="parts_spec" label="规格型号" align="left" width="150">
                <template slot-scope="scope">
                  <el-input v-show="scope.$index === cellIndex" v-model="editSpec" readonly />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.parts_spec }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="parts_brand" label="品牌" align="left" width="180">
                <template slot-scope="scope">
                  <el-input v-show="scope.$index === cellIndex" v-model="editBrand" readonly />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.parts_brand }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="parts_provider" label="供应商" align="left" width="220">
                <template slot-scope="scope">
                  <el-input v-show="scope.$index === cellIndex" v-model="editProvider" readonly />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.parts_provider }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="parts_unit" label="单位" align="left">
                <template slot-scope="scope">
                  <el-input v-show="scope.$index === cellIndex" v-model="editUnit" readonly />
                  <p v-show="scope.$index !== cellIndex">{{ scope.row.parts_unit }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="入库时间" align="left" width="180" />
              <el-table-column prop="total_price" label="合计" align="left" />
              <el-table-column :label="$t('app.handle')" align="left" fixed="right" width="120">
                <template scope="scope">
                  <div v-if="data.status === 1">
                    <el-button v-if="scope.$index !== cellIndex" size="small" type="text" @click="editTable(scope)">{{ $t('button.edit') }}</el-button>
                    <el-button v-else size="small" type="text" @click="saveTable(scope)">保存</el-button>
                    <el-button v-if="scope.$index !== cellIndex" class="delBtn" type="text" size="small" @click="partsDel(scope.row.id)">{{ $t('button.delete') }}</el-button>
                    <el-button v-else size="small" type="text" @click="cancelTable(scope)">取消</el-button>
                  </div>
                  <div v-else>
                    <span>-</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="appear-input">
              <el-form :model="data" inline>
                <el-row v-if="canConfirm" style="padding-top: 20px" :gutter="20">
                  <el-col :span="4">
                    <el-form-item label="备件-编号">
                      <Selects v-model="parts_id" action="partsList" :query="{ add_field: 'coding' }" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="数量">
                      <el-input v-model="number" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="价格">
                      <el-input v-model="price" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="提报日期">
                      <el-date-picker
                        v-model="apply_date"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期时间"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-form-item label="操作">
                      <el-button icon="el-icon-upload2" @click="partsSubmit" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="描述">
          <el-row v-if="editId" :gutter="20" style="padding: 2px">
            <el-col :span="4">
              <div>
                <p>创建时间日期</p>
                <el-input v-model="data.create_time" clearable readonly />
              </div>
              <div>
                <p>创建人</p>
                <el-input v-model="data.create_admin" clearable readonly />
              </div>
              <div v-if="data.update_time">
                <p>最近更新</p>
                <el-input v-model="data.update_time" clearable readonly />
                <p>更新者</p>
                <el-input v-model="data.update_admin" clearable readonly />
              </div>
            </el-col>
            <el-col :span="16">
              <TinyMce v-model="data.content" />
            </el-col>
            <el-col class="upload" :span="4">
              <Adjunct :pk="editId" table="partsEnter" />
            </el-col>
          </el-row>
          <el-row v-if="!editId" :gutter="20" style="padding: 2px">
            <el-col :span="24">
              <TinyMce v-model="data.content" />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import API from '@/api/stock/enter'
import SelfSelect from '@/components/select-o'
import Selects from '@/components/select-search'
import TinyMce from '@/components/Tinymce/index'
import Adjunct from '@/components/Upload/adjunct'
import { mapGetters } from 'vuex'
import { enterOption, enterType } from '@/utils/option'
import XLSX from 'xlsx'
import PARTS from '@/api/stock/parts'
export default {
  inject: ['goUrl', 'isEdit', 'add', 'update', 'reload'],
  components: {
    SelfSelect,
    Selects,
    TinyMce,
    Adjunct
  },
  data() {
    return {
      data: {
        status: 1,
        sort: 1
      },
      canConfirm: false,
      partsNumber: null,
      partsProvider: null,
      editDepartment: null,
      editProvider: null,
      editSpec: null,
      editCategory: null,
      partsCoding: null,
      partsStore: null,
      partsSpec: null,
      partsPrice: null,
      partsUnit: null,
      editId: null,
      editUnit: null,
      editPrice: null,
      editNumber: null,
      editPartsId: null,
      editApplyDate: null,
      editApplyNumber: '',
      editApplyAdminId: null,
      editDate: null,
      editBrand: null,
      title: '',
      parts_id: null,
      number: null,
      price: null,
      loading: true,
      apply_date: null,
      apply_admin_id: null,
      apply_number: null,
      cellIndex: null,
      enterOption,
      enterType,
      rules: {
        coding: { required: true, message: '请输入编号', trigger: 'change' },
        name: { required: true, message: '请输入名称', trigger: 'change' },
        store_id: { required: true, message: '请选择仓库', trigger: 'change' },
        sort: { required: true, message: '请输入排序', trigger: 'change' },
        type: { required: true, message: '请选择来源', trigger: 'change' }
      }
    }
  },
  created() {
    const edit = this.isEdit()
    if (edit) {
      this.title = this.$t('route.stock.enter.detail')
      this.editId = edit
      this.info()
    } else {
      this.loading = false
      this.title = this.$t('route.stock.enter.create')
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  methods: {
    goBack() {
      this.$router.push('/stock/enter')
    },
    info() {
      API.getOne(this.editId).then(res => {
        this.data = res.data
        this.grant()
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
    examine() {
      this.data.status = 2
      const params = {
        id: this.editId,
        status: 2
      }
      API.review(params).then(res => {
        if (res.data.error_code === 1) {
          this.$message({
            message: '审核成功',
            type: 'success'
          })
          this.$router.push('/stock/enter')
        } else {
          this.$message.error('审核失败，请联系管理员')
        }
      })
    },
    workbook(file) {
      this.loading = true
      const reader = new FileReader()
      const self = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        const postData = {}
        postData.outData = outData
        postData.enterId = self.editId
        API.excel(postData).then(response => {
          if (response.data.error_code === 1) {
            self.$message.success(`恭喜你，操作成功`)
            this.loading = false
            self.info()
          } else {
            self.$message.error(response.data.message)
            this.loading = false
            self.info()
          }
        }).finally(() => {
          this.loading = false
        })
      }
      this.loading = false
      reader.readAsBinaryString(file)
      return false
    },
    partsSubmit() {
      console.log(this.apply_date)
      const partsData = {
        enter_id: this.editId,
        parts_id: this.parts_id,
        number: this.number,
        price: this.price,
        apply_date: this.apply_date
      }
      API.append(partsData).then(res => {
        if (res.data.error_code === 1) {
          this.$message.success('新增成功')
          this.info()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    cancelTable(v) {
      this.cellIndex = null
      this.info()
    },
    partsChange(id) {
      if (id === '') {
        this.clear()
      } else {
        PARTS.partsList({ id }).then(res => {
          this.editNumber = null
          console.log(id)
          this.editPrice = res.data.data[0].price
          this.editApplyDate = null
          this.editDepartment = res.data.data[0].department
          console.log(this.editDepartment)
          this.editUnit = res.data.data[0].unit
          this.editProvider = res.data.data[0].provider
          this.editSpec = res.data.data[0].spec
          this.editCategory = res.data.data[0].category
          this.editBrand = res.data.data[0].brand
        })
      }
    },
    clear() {
      this.editPartsId = null
      this.editNumber = null
      this.editPrice = null
      this.editApplyDate = null
      this.editApplyAdminId = null
      this.editApplyNumber = null
      this.editBrand = null
      this.editUnit = null
      this.editProvider = null
      this.editSpec = null
      this.editDepartment = null
      this.editCategory = null
    },
    delBtn() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = this.editId
        API.delete(id).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.$message.success('删除成功')
            this.goBack()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    editTable({ $index, row }) {
      // 获取当前点击行下标
      this.cellIndex = $index
      this.editPartsId = row.parts_id
      this.editNumber = row.number
      this.editPrice = row.price
      this.editApplyDate = row.apply_date
      this.editApplyAdminId = row.apply_admin_id
      this.editApplyNumber = row.apply_number
      this.editBrand = row.parts_brand
      this.editUnit = row.parts_unit
      this.editProvider = row.provider
      this.editSpec = row.parts_spec
      this.editDepartment = row.parts_department
      this.editCategory = row.parts_category
    },
    saveTable({ row }) {
      this.cellIndex = null
      const partsData = {
        id: row.id,
        enter_id: this.editId,
        parts_id: this.editPartsId,
        number: this.editNumber,
        price: this.editPrice,
        apply_date: this.editApplyDate
        // price: parseInt(this.editPrice)
      }
      API.edit(partsData).then(res => {
        if (res.data.error_code !== 1) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('更新成功')
        }
      }).finally(() => {
        this.reload()
      })
    },
    partsDel(id) {
      API.remove(id).then(res => {
        if (res.data.error_code !== 1) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('删除成功')
        }
      }).finally(() => {
        this.info()
      })
    },
    submitForm() {
      if (this.editId) {
        this.update(API, this.data, this.$refs['form'], '/stock/enter')
      } else {
        this.add(API, this.data, this.$refs['form'], '/stock/enter/edit/')
      }
    },
    grant() {
      if ([1].includes(this.data.status)) {
        this.canConfirm = true
      }
    }
  }
}
</script>

<style scoped>
.input{
  width: 100%;
  display: flex;
  margin: 14px 0 8px;
}

</style>
